package org.bjf.modules.core.web.interceptor;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.bjf.exception.CommMsgCode;
import org.bjf.exception.ServiceException;
import org.bjf.utils.SignUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 签名校验拦截器
 *
 * @author binjinfeng
 */
@Component
@Slf4j
public class SignInterceptor extends HandlerInterceptorAdapter {

  @Override
  public boolean preHandle(HttpServletRequest request,
      HttpServletResponse response, Object handler) {
    Map<String, String[]> parameterMap = request.getParameterMap();
    validSign(parameterMap);

    return Boolean.TRUE;
  }

  private void validSign(Map<String, String[]> parameterMap) {
    String sign = parameterMap.get("sign")[0];

    //===1.取出签名字段
    Map<String, String> signMap = new HashMap<>();
    for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
      if (entry.getValue().length > 1) {
        //　数组不参与签名
        continue;
      }
      signMap.put(entry.getKey(), entry.getValue()[0]);
    }

    //===2.验证签名
    String mySign = SignUtil.sign(signMap);
    if (!mySign.equals(sign)) {
      throw new ServiceException(CommMsgCode.INVALID_SIGN);
    }
  }
}
